<template>
  <div>
    <el-card>
      <CategroySelector :isShowList="isShowList" @changeCategory="changeCategory"></CategroySelector>
    </el-card>

    <el-card style="margin-top: 20px">
      <!-- 列表页面 -->
      <div v-show="isShowList">
         <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="showAddDiv">添加属性</el-button>
      <el-table
        border
        :data="attrList"
        style="width: 100%">
        
        <el-table-column
          type="index"
          align="center"
          prop="prop"
          label="序号"
          width="80">
        </el-table-column>

        <el-table-column
          prop="attrName"
          label="属性名称"
          width="150">
        </el-table-column>

        <el-table-column
          prop="prop"
          label="属性值列表"
          width="width">
          <template slot-scope="{row,$index}">
            <el-tag type="success" v-for="attrValue in row.attrValueList " :key="attrValue.id">
              {{attrValue.valueName}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="prop"
          label="操作"
          width="150">
          <template slot-scope="{row,$index}">
            <HintButton type="warning" size="mini" icon="el-icon-edit" title="修改" @click="showUpdateDiv(row)"></HintButton>
            <HintButton type="danger" size="mini" icon="el-icon-delete" title="删除" @click="deleteAttr(row)"></HintButton>
          </template>
        </el-table-column>

      </el-table>
      </div>
     <!-- 添加或修改页面 -->
     <div v-show="!isShowList">
       
      <el-form :inline="true" :model="attrForm"> 
        <el-form-item label="属性名">
          <el-input v-model="attrForm.attrName" placeholder="请输入属性名"></el-input>
        </el-form-item>
      </el-form>

        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrForm.attrName">添加属性值</el-button>
        <el-button>取消</el-button>

        <el-table
          border
          :data="attrForm.attrValueList"
          style="width: 100%;margin:20px 0">
          <el-table-column
            type="index"
            prop="prop"
            label="序号"
            width="80">
          </el-table-column>
          
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width">
            <template slot-scope="{row,$index}">
              <el-input
                :ref="$index"
                v-if="row.isEdit" 
                v-model="row.valueName" 
                @blur="toLook(row)" 
                @keyup.enter.native="toLook(row)"
                size="mini"
                placeholder="请输入属性名称"
                ></el-input>
              <span 
                v-else 
                style="display:block;width:100%" 
                @click="toEdit(row,$index)"
                >{{row.valueName}}</span>
            </template>
          </el-table-column>
          
          <el-table-column
            prop="prop"
            label="操作"
            width="width">
            <template slot-scope="{row,$index}">

              <el-popconfirm
                :title="`你确定删除${row.valueName}吗`"
                @onConfirm="attrForm.attrValueList.splice($index,1)"
              >
                <HintButton type="danger" slot="reference" size="mini" icon="el-icon-delete" title="删除"></HintButton>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" @click="save" :disabled="attrForm.attrValueList.length === 0">保存</el-button>
        <el-button  @click="isShowList = true">取消</el-button>
     
     </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: "AttrList",
  data() {
    // data内部不能使用this
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList:[],
      isShowList:true,
      // 收集数据最终收集成什么样子,是从接口文档来的
      attrForm:{
        attrName: "",
        categoryLevel: 3,
        categoryId: 0,
        attrValueList: [
          // {
          //   attrId: 0,
          //   id: 0,
          //   valueName: "string"
          // }
        ],
      },
    };
  },
  methods: {
    // 获取子组件传递过来的数据
    changeCategory({ categoryId, level }) {
      if (level === 1) {
        this.category1Id = categoryId;
        // 父组件获取到一级ID,清空二三级ID以及内容
        this.category2Id = ""
        this.category3Id = ""
        this.attrList = []
      } else if (level === 2) {
        // 父组件获取到二级ID,清空三级ID以及内容
        this.category2Id = categoryId;
        this.category3Id = ""
        this.attrList = []
      } else {
        // 父组件获取到三级ID,请求获取到属性列表数据
        this.category3Id = categoryId;
        // 父组件获取到三级ID,清空内容
        this.attrList = []
        this.getAttrList();
      }
    },
    // 获取属性数据
    async getAttrList() {
      let {category1Id,category2Id,category3Id} = this
      try {
        const result = await this.$API.attr.getList(category1Id,category2Id,category3Id)
        if (result.code === 200 || result.code === 20000) {
          this.attrList = result.data
        }
      } catch (error) {
        this.$message.error('获取属性列表失败' + error.message)
      }   
    },
    // 点击出现添加属性也页面
    showAddDiv(){
      this.isShowList = false
      this.attrForm = {
        attrName: "",
        categoryLevel: 3,
        categoryId: this.category3Id,
        attrValueList: [
          // {
          //   attrId: 0,
          //   id: 0,
          //   valueName: "string"
          // }
        ],
      }
    },
    // 点击添加一个对象进去  占位思想
    addAttrValue(){
      // 添加一个空对象进去,让table能出现一行
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,//获取的当前属性所属属性的id,添加属性就没有,是undefined,修改的时候就有
        valueName: "",
        isEdit:true,//由于是新添加的属性值,那么isEdit是ture代表目前应该是编辑模式
      })
      this.$nextTick(()=>{
          this.$refs[this.attrForm.attrValueList.length - 1].focus()
        })
    },
    // 点击修改
    showUpdateDiv(row){
      this.isShowList = false
      // 由于属性对象当中属性值列表也是对象数据,浅拷贝属性值列表数据还是同一个,所以浅拷贝搞不定对象内部的对象数据
      this.attrForm = cloneDeep(row)
      this.attrForm.attrValueList.forEach(item => {
        // return item.isEdit = false  不是响应式数据
        this.$set(item,'isEdit,false')
      })
    },
    // span变成查看模式
    toLook(row){
      // 判断用户有没有输入有效的内容
      if (row.valueName.trim() === '' ) {
        row.valueName = ''
        return
      }

      // 判断除了自己以外是不是和其他的属性名重复
      const isTure =  this.attrForm.attrValueList.some((item) => {
        if (item !== row) {
          return item.valueName === row.valueName
        }
      })
      // 
      if (isTure) {
        this.$message.error('请不要输入一样的内容')
        return
      }
      row.isEdit = false
    },
    // 点击input框切换到input框
    toEdit(row,index){
      row.isEdit = true
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 点击保存按钮
    async save(){
      // 1、属性值名称如果为空串，从属性值列表当中去除
      // 2、属性值当中去除isEdit属性
      let attr = this.attrForm
      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName !== '') {
          delete item.isEdit
          return true
        }
      })
      // 3、属性值列表如果没有属性值，不发请求
      if (attr.attrValueList.length === 0) {
        this.message.info('属性值必须要有内容')
        return
      }
      try {
        const result = await this.$API.attr.addOrUpdate(attr)
        if (result.code === 200 || result.code === 20000) {
          this.$message.success('属性值添加成功')
          this.isShowList = true
          this.getAttrList()
        }
      } catch (error) {
        this.$message.error('属性值添加失败')       
      }
    },
    async deleteAttr(row){
      try {
        const result = await this.$API.attr.delete(row.id)
        if (result.code === 200 || result.code === 20000) {
          this.$message.success('删除属性成功')
          this.getAttrList()
        }else{
          this.$message.error('删除属性失败')
        }
      } catch (error) {
        this.$message.error('删除属性失败')
      } 
    }
  },
};
</script>

<style scoped>
</style>
